package cn.tuling;

/**
 * 孙悟空拔毛复制
 * <p>
 * 深拷贝：非基本数据类型属性与原型对象不一样
 * 浅拷贝：非基本数据类型属性与原型对象指向同一个对象的内存地址
 */
public class PrototypeTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sunwukong sunwukong = new Sunwukong("孙悟空", 9999, new MonkeyInfo());
        Sunwukong clone = sunwukong.clone();
        System.out.println(sunwukong);
        System.out.println(clone);
    }
}

class MonkeyInfo implements Cloneable {
    private int tailCount = 1;

    public int getTailCount() {
        return tailCount;
    }

    public void setTailCount(int tailCount) {
        this.tailCount = tailCount;
    }

    @Override
    protected MonkeyInfo clone() throws CloneNotSupportedException {
        return ((MonkeyInfo) super.clone());
    }

    @Override
    public String toString() {
        return super.hashCode() + "] MonkeyInfo{" +
                "tailCount=" + tailCount +
                '}';
    }
}

class Sunwukong implements Cloneable {
    private String name;
    private int age;
    private MonkeyInfo monkeyInfo;

    public Sunwukong(String name, int age, MonkeyInfo monkeyInfo) {
        this.name = name;
        this.age = age;
        this.monkeyInfo = monkeyInfo;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setMonkeyInfo(MonkeyInfo monkeyInfo) {
        this.monkeyInfo = monkeyInfo;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public MonkeyInfo getMonkeyInfo() {
        return monkeyInfo;
    }

    @Override
    protected Sunwukong clone() throws CloneNotSupportedException {
        Sunwukong clone = (Sunwukong) super.clone();
        MonkeyInfo info = monkeyInfo.clone();
        clone.setMonkeyInfo(info);
        return clone;
    }

    @Override
    public String toString() {
        return super.hashCode() + "] Sunwukong{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", monkeyInfo=" + monkeyInfo +
                '}';
    }
}
